//
//  WBPhotoViewerViewController.swift
//  微博Demo
//
//  Created by 花化华 on 2016/11/29.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SDWebImage

class WBPhotoViewerViewController: UIViewController {

    ///创建scrollView
    lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView(frame: self.view.bounds)
        return scrollView
    }()
    
    //创建imageView
    lazy var imageView: UIImageView = UIImageView()
    
    /// 当前是第几张图片
    var index: Int
    /// 当前的图片的url
    var url: String
    
    /// 构造函数
    init(index: Int, url: String) {
        self.index = index
        self.url = url
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

}


// MARK: - 设置UI
extension WBPhotoViewerViewController {
    fileprivate func setupUI() {
        //设置背景色
        view.backgroundColor = UIColor.black
        
        //添加子控件
        view.addSubview(scrollView)
        scrollView.addSubview(imageView)
        
        //加载图片
        loadImage()
    }
    
    fileprivate func loadImage () {
        //获取图片url
        let imageURL = URL(string: url)
        //设置图片
        SDWebImageManager.shared().downloadImage(with: imageURL, options: [], progress: nil) {
            (downloadImage, _, _, _, _) in
            
            //设置图片
            self.imageView.image = downloadImage
            
            //等比重新计算宽高
            var size = (downloadImage?.size)!
            let height = screenWidth * size.height / size.width
            size.width = screenWidth
            size.height = height
            
            //设置图片frame
            self.imageView.frame = CGRect(origin: CGPoint.zero, size:size)
            
            //如果高度小于等于屏幕的高度,则居中显示
            if height <= self.view.bounds.height {
                self.imageView.center = self.scrollView.center
            }
            //如果高度大于屏幕高度,则设置其contentSize,让其可以滚动
            else {
                self.scrollView.contentSize = size
            }
        }
    }
}
